package com.easymall.filter;

import com.easymall.domain.User;
import com.easymall.service.UserService;
import com.easymall.util.BaseFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigInteger;

@WebFilter(filterName = "AutologinFilter")
public class AutologinFilter implements Filter {

    private UserService userService;

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpSession session = request.getSession();

        // 获取autologin cookie
        Cookie[] cookies = request.getCookies();
        Cookie cookie = null;
        for (Cookie tempCookie :
            cookies) {
            if ("autologin".equals(tempCookie.getName())) {
                cookie = tempCookie;
                break;
            }
        }

        if (null != cookie) {
            // autologin cookie存在
            if (null == session.getAttribute("user")) {
                // 没有登陆
                String value = cookie.getValue();
                String[] values = value.split("#");
                if (2 == values.length) {
                    try {
                        int uid = Integer.valueOf(values[0]);
                        String hashCode = values[1];
                        User user = userService.getUserById(uid);
                        String userHashCode = new BigInteger(String.valueOf(user.hashCode())).toString(16);
                        if (userHashCode.equals(hashCode)) {
                            // 用户认证通过，session作用域添加User对象，更新有效期
                            session.setAttribute("user", user);
                            cookie.setMaxAge(30*24*3600);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        cookie.setMaxAge(0);
                        cookie.setValue("");
                    }
                }
            } else {
                // 已经登陆，更新有效期
                cookie.setMaxAge(30*24*3600);
            }
            response.addCookie(cookie);
        }
        chain.doFilter(req, resp);
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        try {
            userService = BaseFactory.getFactory().getInstance(UserService.class);
        } catch (Exception e) {
            e.printStackTrace();
            throw  new ServletException(e.getMessage());
        }

    }

}
